package cn.wit.db.security;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.wit.db.entity.AjaxResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

@Component
public class AuthFailureHandler implements AuthenticationFailureHandler {
	private static final Logger logger = LoggerFactory.getLogger(AuthFailureHandler.class);

	@Autowired
	private ObjectMapper mapper;

	@Override
	public void onAuthenticationFailure(
			HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) 
		throws IOException, ServletException {
		
		logger.warn("登陆失败！{}", exception.getMessage());
		
		String message = null;
		if (exception instanceof BadCredentialsException) {
			message = "用户名或者密码错误！";
		} else {
			message = exception.getMessage();
		}
		
		AjaxResult result = new AjaxResult(500, message);
		response.setContentType("application/json;charset=utf-8");
		
		String content = mapper.writeValueAsString(result);

		response.getWriter().write(content);
	}
}
